<?php
use Medoo\Medoo;

require_once __DIR__ . '/../vendor/autoload.php';

session_start();

// 包含.env文件配置
// $env = file_get_contents( __DIR__ . '/../../../../.env');
// $env_array = explode('\n', $env);\
$filter  = array();
/* 过滤关键字读取开始 */
$file = __DIR__ . '/../../../../.env';
if (file_exists($file)){
    $file_handle = fopen($file, "r");
    while (!feof($file_handle)) {
        $line = fgets($file_handle);
        $str = trim($line);
        if(empty($str)) continue;
        $arr = explode('=', trim($line));
        $filter[$arr[0]] = $arr[1] ?? '';
    }
    fclose($file_handle);
}
/* 过滤关键字读取结束   */
// var_dump($filter);
$env_config = $filter;
if(empty($env_config['DB_CONNECTION'])) {
    exit('请检查服务器配置');
}

$DB = new Medoo([
    'database_type' => $env_config['DB_CONNECTION'],
    'database_name' => $env_config['DB_DATABASE'],
    'server' => $env_config['DB_HOST'],
    'username' => $env_config['DB_USERNAME'],
    'password' => $env_config['DB_PASSWORD'],
    'charset' => 'utf8',
]);

$akid = 'LTAI4GGCjS5yoQJc48XTc7FB';
$aksec = 'CkU5u5qpevqp7os38zQHq4bB2bRwAv';
$endpoint = "http://oss-cn-hangzhou.aliyuncs.com";

$CDN_URL = 'https://www.bkdau.cn/damai/lyfen';

$REDIS = new Redis();
$REDIS->connect($env_config['REDIS_HOST'], $env_config['REDIS_PORT']);
if(!empty($env_config['REDIS_PASSWORD'])) {
    $REDIS->auth($env_config['REDIS_PASSWORD']);
}

define('Login_Secret', 'bu~1yu.>@]^you$(xi666');
define("LOG_MODULE", [
    'exchange' => [
        'name' => '兑换商品',
        'action' => [
            'delete_item' => '删除商品',
            'godown_item' => '下架商品',
            'goup_item' => '上架商品',
            'new_item' => '添加商品',
            'edit_item' => '修改商品',
        ],
    ],
	'player' => [
		'name' => '玩家管理',
		'action' => [
			'send_mail' => '群发邮件',
			'change_gem' => '修改钻石',
			'change_gold' => '修改金币',
			'freeze' => '冻结账号',
			'un_freeze' => '解冻账号',
			'change_limit' => '修改输赢控制',
			'change_win_lose' => '修改输赢区间',
			'change_water' => '修改抽水',
			'change_configedit' => '修改充值兑换账户',
			'change_item' => '修改道具',
		],
	],
	'task' => [
		'name' => '任务管理',
		'action' => [
			'edit_task' => '修改任务',
		],
	],
	'message' => [
		'name' => '消息推送',
		'action' => [
			'send_message' => '消息推送',
		],
	],
	'spread' => [
		'name' => '推广员系统',
		'action' => [
			'withdraw_agree' => '同意提现',
			'withdraw_refuse' => '拒绝提现',
			'bind' => '补绑师徒关系',
		],
	],
	'super' => [
		'name' => '后台系统管理',
		'action' => [
			'new_group' => '新建账号分组',
			'change_group' => '修改分组信息',
			'delete_group' => '删除账号分组',
			'new_user' => '新建后台账号',
			'change_funcs' => '修改后台账号权限',
			'freeze' => '冻结后台账号',
			'un_freeze' => '解冻后台账号',
			'change_pass' => '修改后台账号密码',
			'delete' => '删除后台账号',
		],
	],
	'notice' => [
		'name' => '公告管理',
		'action' => [
			'sync' => '同步全服公告',
			'pushon' => '上架',
			'pulloff' => '下架',
			'edit' => '编辑公告',
			'add' => '添加公告',
			'delete' => '删除公告',
		],
	],
	'login' => [
		'name' => '登录登出',
		'action' => [
			'login' => '登录',
			'logout' => '登出',
		],
	],
	'active_rank' => [
		'name' => '活跃度排行榜管理',
		'action' => [
			'edit_banner' => '修改banner',
			'edit_strategy' => '修改活动攻略',
			'edit_reward' => '编辑排行榜奖励',
		],
	],
]);

global $config_item;
$config_item = [
	0=>'快速获取经验',
	1=>'自动发炮',
	2=>'锁定',
	3=>'急速发炮',
	14=>'珍珠',
	41=>'普通鱼雷',
	42=>'白银鱼雷',
	43=>'黄金鱼雷',
	44=>'紫金鱼雷',
	45=>'七彩鱼雷',
];

function getContribution($uid, $need_data=false) {
	$contri = [
		'total_contri'  => 0,
		'total_valid'   => 0,
		'total_tudi'    => 0,
		'total_tusun'   => 0,
		'frozen_tudi'   => 0,
		'frozen_tusun'  => 0,
		'receive_tudi'  => 0,
		'receive_tusun' => 0,
		'valid_tudi'    => 0,
		'valid_tusun'   => 0,
		'contri_detail' => [],
	];
	if(!$uid) return $contri;

	global $plat_db;
	$get_user = $plat_db->select('uid,contri1,contri2,frozen1,frozen2,receive1,receive2')->from('user_contri')->where("uid=$uid")->row();
	if(!isset($get_user['uid'])) return $contri;
	$contri['total_contri']  = $get_user['contri1'] + $get_user['contri2'];
	$contri['total_tudi']    = $get_user['contri1'];
	$contri['total_tusun']   = $get_user['contri2'];
	$contri['frozen_tudi']   = $get_user['frozen1'];
	$contri['frozen_tusun']  = $get_user['frozen2'];
	$contri['receive_tudi']  = $get_user['receive1'];
	$contri['receive_tusun'] = $get_user['receive2'];
	$contri['valid_tudi']    = $get_user['contri1'] - $get_user['frozen1'] - $get_user['receive1'];
	$contri['valid_tusun']   = $get_user['contri2'] - $get_user['frozen2'] - $get_user['receive2'];
	$contri['total_valid']   = $contri['valid_tudi'] + $contri['valid_tusun'];

	if($need_data === true) {
		$all_contri = $plat_db->select('child,num')->from('user_contri_history')->where("uid=$uid")->query();
		if (!empty($all_contri)) {
			foreach ($all_contri as $c) {
				if ($c['child'] > 0) {
					@$contri['contri_detail'][$c['child']] += $c['num'];
				} else {
					@$contri['contri_detail'][0] += $c['num'];
				}
			}
		}
	}

	return $contri;
}

function operate_log($module, $action, $params=[]) {
	global $_SESSION;
	global $DB;
    $DB->insert('admin_operation_log', [
		'module' => $module,
		'action' => $action,
		'params' => json_encode($params, JSON_UNESCAPED_UNICODE),
		'user'   => $_SESSION['admin_id'],
		'time'   => time(),
		'ip'     => ip2long(getIP()),
	]);
}

function getIP() {
	if     (getenv('HTTP_CLIENT_IP'))		$ip = getenv('HTTP_CLIENT_IP');
	elseif (getenv('HTTP_X_FORWARDED_FOR')) $ip = getenv('HTTP_X_FORWARDED_FOR');
	elseif (getenv('HTTP_X_FORWARDED')) 	$ip = getenv('HTTP_X_FORWARDED');
	elseif (getenv('HTTP_FORWARDED_FOR')) 	$ip = getenv('HTTP_FORWARDED_FOR');
	elseif (getenv('HTTP_FORWARDED')) 		$ip = getenv('HTTP_FORWARDED');
	else 									$ip = $_SERVER['REMOTE_ADDR'];
	return $ip;
}

function display_contri($contri) {
	$rmb = $gold = NULL;
	if($contri >= 10000000) {
		$rmb = intval($contri / 10000000);
		$gold = intval(($contri - ($rmb * 10000000) ) / 10000);
		$contri = $contri - ($rmb * 10000000) - ($gold * 10000);
		return '<div class="col-sm-4">' . $rmb . '<small><i class="fa fa-rmb"></i></small></div>' .
			   '<div class="col-sm-4">' . $gold . '<small>金沙</small></div>' .
			   '<div class="col-sm-4">' . $contri . '<small>贡献</small></div>';
	} else if($contri >= 10000) {
		$gold = intval(($contri - ($rmb * 10000000) ) / 10000);
		$contri = $contri - ($rmb * 10000000) - ($gold * 10000);
		return '<div class="col-sm-4">&nbsp;</div>' .
			   '<div class="col-sm-4">' . $gold . '<small>金沙</small></div>' .
			   '<div class="col-sm-4">' . $contri . '<small>贡献</small></div>';
	} else {
		return $contri . '<small>贡献</small>';
	}
}

function display_contri2($contri) {
	$gold = NULL;
	if($contri >= 1000) {
		$gold = intval($contri/1000);
		$contri = $contri -  ($gold * 1000);
		if($gold >= 100000) {
			$w = intval($gold / 10000);
			$rest = $gold % 10000;
			if($rest < 10) $rest = '000'.$rest;
			else if($rest < 100) $rest = '00'.$rest;
			else if($rest < 1000) $rest = '0'.$rest;
			$gold = $w . ',' . $rest;
		}
		return '<div class="col-sm-4">' . $gold . '<small>金币</small></div>' .
			   '<div class="col-sm-4">' . $contri . '<small>贡献</small></div>';
	} else {
		return '<div class="col-sm-4">0<small>金币</small></div><div class="col-sm-4">' . $contri . '<small>贡献</small></div>';
	}
}

function fetchUrl($url, $method, $body) {
	$ch = curl_init();
	if($method == 'POST') {
		curl_setopt($ch, CURLOPT_POST, 1);//post提交方式
		curl_setopt($ch, CURLOPT_POSTFIELDS, $body);
	} else {
		$url .= '?'.$body;
	}
	curl_setopt($ch, CURLOPT_URL, $url);
	curl_setopt($ch, CURLOPT_TIMEOUT, 5);
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
	curl_setopt($ch, CURLOPT_HTTPHEADER, array(
		"x-sdk-client" => "php/2.0.0"
	));
	if(substr($url, 0,5) == 'https') {
		curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
		curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
	}
	$rtn = curl_exec($ch);
	curl_close($ch);
	return $rtn;
}

function formatBigNumber($num) {
	if($num >= 10000) {
		$wan = intval($num / 10000);
	} else {
		$wan = 0;
	}
	$rest = $num - $wan * 10000;
	$str = '';
	if($wan > 0) {
		$str .= '<span class="wan">'.$wan.'</span><small>万</small>';
	}
	$str .= '<span class="rest">'.$rest.'</span>';
	return $str;
}

function pagination($url, $get, $now_page, $total_num, $pagesize, $is_small=false, $show_output=false) {
	if($total_num < 1) return;
	$total_page = ceil($total_num / $pagesize);

	$start = ($now_page - 1) * $pagesize + 1;
	$end   = $start + $pagesize - 1;

	$url .= '?t=p';
	$qstr = '';
	unset($get['t']);
	unset($get['page']);
	if(!empty($get)) {
		$qarr = [];
		foreach($get as $k => $v) {
			// 翻页时过滤敏感参数
			if(in_array($k, ['success', 'error', 'action'])) continue;
			$qarr[] = $k . '=' . $v;
		}
		$qstr = join('&', $qarr);
		$url .= '&' . $qstr;
	}

	echo '<div class="row" style="margin-top:15px;"><div class="col-sm-4">';
	if($show_output === true) {
		echo '<button class="btn btn-sm bg-olive" style="display:inline-block;float:left;margin-right:20px;" id="export_data">导出数据</button>';
	}
	echo '<div class="dataTables_info" id="example1_info" style="line-height:32px;">显示第 ' . $start . ' 到 ' . $end . ' 条, &nbsp;&nbsp; 共 ' . $total_num . ' 条</div>';
	echo '</div><div class="col-sm-8"><div class="" id="example1_paginate"><ul style="margin:0;" class="pagination ';
	if($is_small) echo 'pagination-sm';
	echo '">';

	echo '<li class="paginate_button  previous ' . (($now_page==1) ? 'disabled' : '') . '"><a '. (($now_page==1) ? 'disabled onclick="return false;"' : '') . ' href="' . $url . ($now_page>1 ? '&page='.($now_page-1) : '') . '" >上一页</a></li>';
	$before = $after = 0;
	$page_limit = 6;
	if($now_page > 1) {
		$before = $now_page - 1;
		if($before > 3) $before = 3;
		$page_limit -= $before;
	}
	if($now_page < $total_page) {
		$after = $total_page - $now_page;
		if($after > $page_limit) {
			$after = $page_limit;
			$page_limit = 0;
		} else {
			$page_limit -= $after;
		}
	}

	if($page_limit > 0) $before += $page_limit;

	if($now_page >= 5) {
		echo '<li class="paginate_button"><a href="' . $url . '&page=1">1</a></li><li class="paginate_button"><a>...</a></li>';
	}

	$count = 0;
	$before_arr = [];
	for($i=$now_page-1; $i>0; $i--) {
		$count++;
		if($count > $before) break;
		$before_arr[] = '<li class="paginate_button"><a href="' . $url . '&page=' . $i . '">' . $i . '</a></li>';
	}
	$before_arr = array_reverse($before_arr);
	foreach($before_arr as $b) { echo $b; }

	echo '<li class="paginate_button active"><a href="' . $url . '&page=' . $now_page . '">' . $now_page . '</a></li>';

	$count = 0;
	for($i=$now_page+1; $i<=$total_page; $i++) {
		if($count >= $after) break;
		$count++;
		echo '<li class="paginate_button"><a href="' . $url . '&page=' . $i . '">' . $i . '</a></li>';
	}

	if($now_page < ($total_page - 3)) {
		echo '<li class="paginate_button"><a>...</a></li><li class="paginate_button"><a href="' . $url . '&page=' . $total_page . '">' . $total_page . '</a></li>';
	}

	echo '<li class="paginate_button previous ' . (($now_page==$total_page) ? 'disabled' : '') . '"><a '. (($now_page==$total_page) ? 'disabled onclick="return false;"' : '') . ' href="' . $url . ($now_page<$total_page ? '&page='.($now_page+1) : '') . '" >下一页</a></li>';

	echo '</ul></div></div></div></div></div>';
}

function pagination4($url, $get, $now_page, $total_num, $pagesize, $is_small=false) {
	if($total_num < 1) return;
	$total_page = ceil($total_num / $pagesize);

	$start = ($now_page - 1) * $pagesize + 1;
	$end   = $start + $pagesize - 1;

	$url .= '?t=p';
	$qstr = '';
	unset($get['t']);
	unset($get['page']);
	if(!empty($get)) {
		$qarr = [];
		foreach($get as $k => $v) {
			// 翻页时过滤敏感参数
			if(in_array($k, ['success', 'error', 'action'])) continue;
			$qarr[] = $k . '=' . $v;
		}
		$qstr = join('&', $qarr);
		$url .= '&' . $qstr;
	}

	echo '<div class="row" style="margin-top:15px;"><div class="col-sm-4">';
	echo '<div class="dataTables_info" id="example1_info" style="line-height:32px;">显示第 ' . $start . ' 到 ' . $end . ' 条, &nbsp;&nbsp; 共 ' . $total_num . ' 条</div>';
	echo '</div><div class="col-sm-8"><nav aria-label="Page navigation example"><ul style="margin:0;" class="pagination ';
	if($is_small) echo 'pagination-sm';
	echo '">';

	echo '<li class="page-item  previous ' . (($now_page==1) ? 'disabled' : '') . '"><a class="page-link" '. (($now_page==1) ? 'disabled onclick="return false;"' : '') . ' href="' . $url . ($now_page>1 ? '&page='.($now_page-1) : '') . '" >上一页</a></li>';
	$before = $after = 0;
	$page_limit = 6;
	if($now_page > 1) {
		$before = $now_page - 1;
		if($before > 3) $before = 3;
		$page_limit -= $before;
	}
	if($now_page < $total_page) {
		$after = $total_page - $now_page;
		if($after > $page_limit) {
			$after = $page_limit;
			$page_limit = 0;
		} else {
			$page_limit -= $after;
		}
	}

	if($page_limit > 0) $before += $page_limit;

	if($now_page >= 5) {
		echo '<li class="page-item"><a class="page-link" href="' . $url . '&page=1">1</a></li><li class="page-item"><a>...</a></li>';
	}

	$count = 0;
	$before_arr = [];
	for($i=$now_page-1; $i>0; $i--) {
		$count++;
		if($count > $before) break;
		$before_arr[] = '<li class="page-item"><a class="page-link" href="' . $url . '&page=' . $i . '">' . $i . '</a></li>';
	}
	$before_arr = array_reverse($before_arr);
	foreach($before_arr as $b) { echo $b; }

	echo '<li class="page-item active"><a class="page-link" href="' . $url . '&page=' . $now_page . '">' . $now_page . '</a></li>';

	$count = 0;
	for($i=$now_page+1; $i<=$total_page; $i++) {
		if($count >= $after) break;
		$count++;
		echo '<li class="page-item"><a class="page-link" href="' . $url . '&page=' . $i . '">' . $i . '</a></li>';
	}

	if($now_page < ($total_page - 3)) {
		echo '<li class="page-item"><a class="page-link">...</a></li><li class="page-item"><a class="page-link" href="' . $url . '&page=' . $total_page . '">' . $total_page . '</a></li>';
	}

	echo '<li class="page-item previous ' . (($now_page==$total_page) ? 'disabled' : '') . '"><a class="page-link" '. (($now_page==$total_page) ? 'disabled onclick="return false;"' : '') . ' href="' . $url . ($now_page<$total_page ? '&page='.($now_page+1) : '') . '" >下一页</a></li>';

	echo '</ul></nav></div></div></div></div>';
}
